<template>
  <ContentWrap v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="dynamicFormRules"
      label-width="100px"
    >
      <el-card class="section-card" shadow="never">
        <template #header>接触限值</template>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="危害分类" prop="type">
              <el-select v-model="formData.type" placeholder="请选择危害分类">
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.HAZARD_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="中文名" prop="cnName">
              <el-input v-model="formData.cnName" placeholder="请输入中文名" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="首字母" prop="letter">
              <el-input v-model="formData.letter" placeholder="请输入首字母" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="英文名称" prop="enName">
              <el-input v-model="formData.enName" placeholder="请输入英文名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6" v-if="isShowColum">
            <el-form-item prop="whgroup">
              <template #label>
                <el-tooltip
                  content="同一组别的采样时会进行合并采样"
                  effect="light"
                  placement="top"
                >
                  <span  >合并组别</span>
                </el-tooltip>
              </template>
              <el-select v-model="formData.whgroup" placeholder="请选择合并组别">
                <el-option label="一组" value="一组" />
                <el-option label="二组" value="二组" />
                <el-option label="三组" value="三组" />
                <el-option label="四组" value="四组" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="CAS" prop="cas">
              <el-input v-model="formData.cas" placeholder="请输入cas" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="MAC" prop="mac">
              <el-input v-model="formData.mac" placeholder="请输入mac"  >
                <template #append>mg/m³</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="PC_TWA" prop="pcTwa">
              <el-input v-model="formData.pcTwa" placeholder="请输入pc_twa"  >
                <template #append>mg/m³</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="PC_STEL" prop="pcStel">
              <el-input v-model="formData.pcStel" placeholder="请输入pc_stel"  >
                <template #append>mg/m³</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="总尘" prop="totalDust">
              <el-input v-model="formData.totalDust" placeholder="请输入总尘" >
                <template #append>mg/m³</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="呼尘" prop="expiratoryDust">
              <el-input v-model="formData.expiratoryDust" placeholder="请输入呼尘"  >
                <template #append>mg/m³</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="note">
              <el-input v-model="formData.note" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="18">
            <el-form-item label="不良健康" prop="healthEffects">
              <el-input v-model="formData.healthEffects" placeholder="请输入临界不良健康效应" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="section-card" shadow="never">
        <template #header>检测方法</template>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="项目分组" prop="jcgroup">
              <el-select v-model="formData.jcgroup" clearable placeholder="请选择分组">
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.JCGROUP)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测标准" prop="testStandard">
              <el-input-tag
                v-model="formData.testStandard"
                :max-collapse-tags="3"
                placeholder="请输入检测依据，按回车确认"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="解析液" prop="resolutionSolution">
              <el-input v-model="formData.resolutionSolution" placeholder="请输入解析液" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="空气收集器" prop="airCollectors">
              <el-input-tag
                v-model="formData.airCollectors"
                :max-collapse-tags="3"
                placeholder="请输入空气收集器，按回车确认"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="测量设备" prop="measuringEquipment">
              <el-input-tag
                v-model="formData.measuringEquipment"
                :max-collapse-tags="3"
                placeholder="请输入测量设备，按回车确认"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保存期限" prop="storageLife">
              <el-input v-model="formData.storageLife" placeholder="请输入保存期限" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="短时间" prop="shortTime">
              <el-input v-model="formData.shortTime" placeholder="请输入短时间">
                <template #append>min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="短时间流量" prop="shortTimeFlow">
              <el-input v-model="formData.shortTimeFlow" placeholder="请输入短时间流量" >
                <template #append>L/min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="长时间" prop="longTime">
              <el-input v-model="formData.longTime" placeholder="请输入长时间" >
                <template #append>min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="长时间流量" prop="longTimeFlow">
              <el-input v-model="formData.longTimeFlow" placeholder="请输入长时间流量"  >
                <template #append>L/min</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="定量下限" prop="dlxx">
              <el-input v-model="formData.dlxx" placeholder="请输入定量下限" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <el-button type="primary" @click="submitForm">确 定</el-button>
    <el-button @click="dialogVisible = false">取 消</el-button>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { computed, nextTick, watch } from 'vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { HazardsApi, HazardsVO } from '@/api/system/hazards'

/** 危害因素 表单 */
defineOptions({ name: 'HazardsForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  type: undefined,
  whgroup: undefined,
  jcgroup: undefined,
  cnName: undefined,
  letter: undefined,
  enName: undefined,
  mergeGroup: undefined,
  cas: undefined,
  mac: '—',
  pcTwa: '—',
  pcStel: '—',
  totalDust: undefined,
  expiratoryDust: undefined,
  healthEffects: undefined,
  testStandard: undefined,
  airCollectors: [],
  storageLife: undefined,
  resolutionSolution: undefined,
  measuringEquipment: undefined,
  samplingMedium: undefined,
  shortTime: undefined,
  shortTimeFlow: undefined,
  longTime: undefined,
  longTimeFlow: undefined,
  dlxx: '—',
  note: undefined,
  volumeSettings: []
})
const formRules = reactive({})

// 动态验证规则 - 当危害分类为粉尘时，增加必填字段
const dynamicFormRules = computed(() => {
  const rules = { ...formRules }

  // 检查是否为粉尘类型（假设粉尘的字典值为 'dust' 或包含 '粉尘' 的标签）
  const isDustType = () => {
    if (!formData.value.type) return false
    const dictOptions = getStrDictOptions(DICT_TYPE.HAZARD_TYPE)
    const selectedDict = dictOptions.find((dict) => dict.value === formData.value.type)
    return selectedDict && selectedDict.label.includes('粉尘')
  }

  // 检查是否为物理因素（通过标签匹配“物理因素”）
  const isPhysicalType = () => {
    if (!formData.value.type) return false
    const dictOptions = getStrDictOptions(DICT_TYPE.HAZARD_TYPE)
    const selectedDict = dictOptions.find((dict) => dict.value === formData.value.type)
    return selectedDict && selectedDict.label.includes('物理因素')
  }

  // 检查是否为化学因素（通过标签匹配“化学因素”）
  const isChemicalType = () => {
    if (!formData.value.type) return false
    const dictOptions = getStrDictOptions(DICT_TYPE.HAZARD_TYPE)
    const selectedDict = dictOptions.find((dict) => dict.value === formData.value.type)
    return selectedDict && selectedDict.label.includes('化学因素')
  }

  // 基础校验：定量浓度集合不能为空（所有类型都适用）

  if (isDustType()) {
    rules.type = [{ required: true, message: '请选择危害分类', trigger: 'change' }]
    rules.cnName = [{ required: true, message: '请输入中文名', trigger: 'blur' }]
    rules.letter = [{ required: true, message: '请输入首字母', trigger: 'blur' }]
    // 粉尘类型时，以下字段为必填
    rules.enName = [{ required: true, message: '请输入英文名称', trigger: 'blur' }]
    rules.totalDust = [{ required: true, message: '请输入总尘', trigger: 'blur' }]
    rules.expiratoryDust = [{ required: true, message: '请输入呼尘', trigger: 'blur' }]

    rules.healthEffects = [{ required: true, message: '请输入临界不良健康效应', trigger: 'blur' }]
    rules.testStandard = [{ required: true, message: '请输入检测依据', trigger: 'blur' }]
    rules.airCollectors = [{ required: true, message: '请输入空气收集器', trigger: 'blur' }]
    rules.storageLife = [{ required: true, message: '请输入保存期限', trigger: 'blur' }]
    rules.shortTimeFlow = [{ required: true, message: '请输入短时间流量', trigger: 'blur' }]
    rules.longTimeFlow = [{ required: true, message: '请输入长时间流量', trigger: 'blur' }]
    rules.dlxx = [{ required: true, message: '请输入定量下限', trigger: 'blur' }]

    // 粉尘类型下的定量浓度表格验证：除了非空，还需逐行必填
  }

  // 物理因素：中文名、首字母、英文名称、检测标准 必填
  if (isPhysicalType()) {
    rules.type = [{ required: true, message: '请选择危害分类', trigger: 'change' }]
    rules.cnName = [{ required: true, message: '请输入中文名', trigger: 'blur' }]
    rules.letter = [{ required: true, message: '请输入首字母', trigger: 'blur' }]
    rules.enName = [{ required: true, message: '请输入英文名称', trigger: 'blur' }]
    rules.testStandard = [{ required: true, message: '请输入检测依据', trigger: 'blur' }]
  }

  // 化学因素：中文名 首字母 英文名称 CAS MAC PC_TWA PC_STEL 备注 不良健康 检测标准 解析液 空气收集器 保存期限 短时间 短时间流量 长时间 长时间流量 定量下限 定量浓度（含逐行校验）
  if (isChemicalType()) {
    rules.type = [{ required: true, message: '请选择危害分类', trigger: 'change' }]
    rules.cnName = [{ required: true, message: '请输入中文名', trigger: 'blur' }]
    rules.letter = [{ required: true, message: '请输入首字母', trigger: 'blur' }]
    rules.enName = [{ required: true, message: '请输入英文名称', trigger: 'blur' }]
    rules.cas = [{ required: true, message: '请输入CAS', trigger: 'blur' }]
    rules.mac = [{ required: true, message: '请输入MAC', trigger: 'blur' }]
    rules.pcTwa = [{ required: true, message: '请输入PC_TWA', trigger: 'blur' }]
    rules.pcStel = [{ required: true, message: '请输入PC_STEL', trigger: 'blur' }]

    rules.healthEffects = [{ required: true, message: '请输入不良健康', trigger: 'blur' }]
    rules.testStandard = [{ required: true, message: '请输入检测依据', trigger: 'blur' }]
    // rules.resolutionSolution = [{ required: true, message: '请输入解析液', trigger: 'blur' }]
    rules.airCollectors = [{ required: true, message: '请输入空气收集器', trigger: 'blur' }]
    rules.storageLife = [{ required: true, message: '请输入保存期限', trigger: 'blur' }]
    rules.shortTime = [{ required: true, message: '请输入短时间', trigger: 'blur' }]
    rules.shortTimeFlow = [{ required: true, message: '请输入短时间流量', trigger: 'blur' }]
    rules.longTime = [{ required: true, message: '请输入长时间', trigger: 'blur' }]
    rules.longTimeFlow = [{ required: true, message: '请输入长时间流量', trigger: 'blur' }]
    rules.dlxx = [{ required: true, message: '请输入定量下限', trigger: 'blur' }]
  }

  return rules
})

const formRef = ref() // 表单 Ref

// 展示条件：当危害分类为“化学因素”或其值等于 '2' 时显示“合并组别”
const isShowColum = computed(() => {
  const typeValue = formData.value.type
  if (!typeValue) return false
  if (String(typeValue) === '2') return true
  const dictOptions = getStrDictOptions(DICT_TYPE.HAZARD_TYPE)
  const selected = dictOptions.find((d) => d.value === typeValue)
  return !!(selected && String(selected.label).includes('化学因素'))
})

// 监听危害分类变化，重新验证并向父组件同步类型
const emit = defineEmits(['success', 'type-change'])
watch(
  () => formData.value.type,
  (newType, oldType) => {
    if (newType !== oldType) {
      emit('type-change', newType)
      if (formRef.value) {
        nextTick(() => {
          formRef.value.clearValidate()
        })
      }
    }
  }
)

/** 打开弹窗 */
const open = async (type: string, id?: number, initialHazardType?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 新增时，将危害分类预设为传入的 tab 值
  if (type === 'create' && initialHazardType) {
    formData.value.type = initialHazardType
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await HazardsApi.getHazards(id)
      // 处理数组字段，将字符串转为数组
      if (data.airCollectors) {
        data.airCollectors = data.airCollectors.split(',')
      }
      if (data.testStandard) {
        data.testStandard = data.testStandard.split(',')
      }
      if (data.measuringEquipment) {
        data.measuringEquipment = data.measuringEquipment.split(',')
      }
      // 采样体积设置：后端以 JSON 字符串存储时，这里解析
      if (typeof data.volumeSettings === 'string') {
        try {
          data.volumeSettings = JSON.parse(data.volumeSettings)
        } catch (e) {
          data.volumeSettings = []
        }
      }
      if (!Array.isArray(data.volumeSettings)) {
        data.volumeSettings = []
      }
      if (data.volumeSettings.length === 0) {
        data.volumeSettings.push(createEmptyVolumeRow())
      }
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单（捕获并友好提示，而不是抛出未捕获异常）
  try {
    await formRef.value.validate()
  } catch (errors: any) {
    try {
      const firstField = errors && Object.keys(errors)[0]
      if (firstField && typeof formRef.value?.scrollToField === 'function') {
        formRef.value.scrollToField(firstField)
      }
    } catch {}
    message.error('请完善必填项后再提交')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as HazardsVO
    // 处理数组字段，将数组转为字符串
    if (Array.isArray(data.airCollectors)) {
      data.airCollectors = data.airCollectors.join(',')
    }
    if (Array.isArray(data.testStandard)) {
      data.testStandard = data.testStandard.join(',')
    }
    if (Array.isArray(data.measuringEquipment)) {
      data.measuringEquipment = data.measuringEquipment.join(',')
    }
    // volumeSettings 序列化（若是对象数组则转为 JSON 字符串）
    if (Array.isArray((data as any).volumeSettings)) {
      ;(data as any).volumeSettings = JSON.stringify((data as any).volumeSettings)
    }
    console.log('提交的表单数据：', JSON.stringify(data))
    if (formType.value === 'create') {
      await HazardsApi.createHazards(data)
      message.success(t('common.createSuccess'))
    } else {
      await HazardsApi.updateHazards(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    type: undefined,
    whgroup: undefined,
    jcgroup: undefined,
    cnName: undefined,
    letter: undefined,
    enName: undefined,
    mergeGroup: undefined,
    cas: undefined,
    mac: '—',
    pcTwa: '—',
    pcStel: '—',
    totalDust: '—',
    expiratoryDust: '—',
    healthEffects: '—',
    testStandard: undefined,
    airCollectors: [],
    storageLife: undefined,
    resolutionSolution: undefined,
    measuringEquipment: undefined,
    samplingMedium: undefined,
    shortTime: undefined,
    shortTimeFlow: undefined,
    longTime: undefined,
    longTimeFlow: undefined,
    dlxx: '—',
    note: '—',
    volumeSettings: [createEmptyVolumeRow()]
  }
  formRef.value?.resetFields()
}

// 采样体积设置 - 行操作
const createEmptyVolumeRow = () => ({ volume: '', minConcentration: '' })

const addVolumeRowAfter = (index: number) => {
  if (!Array.isArray(formData.value.volumeSettings)) {
    formData.value.volumeSettings = []
  }
  formData.value.volumeSettings.splice(index + 1, 0, createEmptyVolumeRow())
  // 触发验证
  nextTick(() => {
    validateVolumeSettings()
  })
}

const removeVolumeRow = (index: number) => {
  formData.value.volumeSettings.splice(index, 1)
  if (formData.value.volumeSettings.length === 0) {
    formData.value.volumeSettings.push(createEmptyVolumeRow())
  }
  // 触发验证
  nextTick(() => {
    validateVolumeSettings()
  })
}

// 验证定量浓度设置
const validateVolumeSettings = () => {
  if (formRef.value) {
    formRef.value.validateField('volumeSettings')
  }
}

// 父组件可主动设置类型保持同步
const setType = (type: string) => {
  formData.value.type = type
}

defineExpose({ open, submitForm, setType }) // 提供 open 方法，用于打开弹窗
</script>
<style scoped>
.section-card {
  margin-bottom: 12px;
}

.section-card :deep(.el-card__header) {
  font-weight: 600;
  padding: 10px 16px;
}

.section-card :deep(.el-card__body) {
  padding-top: 10px;
  padding-bottom: 4px;
}

.no-gap-card :deep(.el-card__body) {
  padding: 0;
}

/* 定量浓度卡片头部右侧展示校验信息，保持表格样式不变 */
.dlnd-header {
  display: flex;
  align-items: center;
  justify-content: flex-start; /* 与标题放在一起 */
  gap: 8px; /* 标题与错误提示之间留空隙 */
}

.dlnd-header :deep(.el-form-item) {
  margin-bottom: 0; /* 不占额外竖向空间 */
}

.dlnd-header__msg :deep(.el-form-item__error) {
  position: static; /* 使错误信息出现在标题右侧 */
}
</style>
